package com.androidbook;

import java.util.ArrayList;
import java.util.Random;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;


class AnimationView extends SurfaceView implements MechanicGame, SurfaceHolder.Callback
{
    public int PosX=6;
	public int PosY=4;
	public int cX=0;
	public int cY=0;
	
	 Bitmap _tlo = BitmapFactory.decodeResource(getResources(), R.drawable.tlo);
	 Bitmap _s0l = BitmapFactory.decodeResource(getResources(), R.drawable.s0l);
	 Bitmap _s0p = BitmapFactory.decodeResource(getResources(), R.drawable.s0p);
	 Bitmap _s1l = BitmapFactory.decodeResource(getResources(), R.drawable.s1l);
	 Bitmap _s1m = BitmapFactory.decodeResource(getResources(), R.drawable.s1m);
	 Bitmap _s1p = BitmapFactory.decodeResource(getResources(), R.drawable.s1p);
	 Bitmap _s2l = BitmapFactory.decodeResource(getResources(), R.drawable.s2l);
	 Bitmap _s2m = BitmapFactory.decodeResource(getResources(), R.drawable.s2m);
	 Bitmap _s2p = BitmapFactory.decodeResource(getResources(), R.drawable.s2p);
	 Bitmap _s3l = BitmapFactory.decodeResource(getResources(), R.drawable.s3l);
	 Bitmap _s3m = BitmapFactory.decodeResource(getResources(), R.drawable.s3m);
	 Bitmap _s3p = BitmapFactory.decodeResource(getResources(), R.drawable.s3p);
	 
	 Bitmap[] hobgob = new Bitmap[] {
			 BitmapFactory.decodeResource(getResources(), R.drawable.hob1),
			 BitmapFactory.decodeResource(getResources(), R.drawable.hob2),
			 BitmapFactory.decodeResource(getResources(), R.drawable.hob3),
			 BitmapFactory.decodeResource(getResources(), R.drawable.hob4),
			 BitmapFactory.decodeResource(getResources(), R.drawable.hob5),
			 BitmapFactory.decodeResource(getResources(), R.drawable.hob6)};
	 
	 Bitmap[] skel = new Bitmap[] {
			 BitmapFactory.decodeResource(getResources(), R.drawable.skel1),
			 BitmapFactory.decodeResource(getResources(), R.drawable.skel2),
			 BitmapFactory.decodeResource(getResources(), R.drawable.skel3),
			 BitmapFactory.decodeResource(getResources(), R.drawable.skel4),
			 BitmapFactory.decodeResource(getResources(), R.drawable.skel5),
			 BitmapFactory.decodeResource(getResources(), R.drawable.skel6)};
	 
	 Bitmap[] kob = new Bitmap[] {
			 BitmapFactory.decodeResource(getResources(), R.drawable.kobold1),
			 BitmapFactory.decodeResource(getResources(), R.drawable.kobold2),
			 BitmapFactory.decodeResource(getResources(), R.drawable.kobold3),
			 BitmapFactory.decodeResource(getResources(), R.drawable.kobold4),
			 BitmapFactory.decodeResource(getResources(), R.drawable.kobold5),
			 BitmapFactory.decodeResource(getResources(), R.drawable.kobold6)};
	 
	 Bitmap[] miecz = new Bitmap[] {
			 BitmapFactory.decodeResource(getResources(), R.drawable.miecz),
			 BitmapFactory.decodeResource(getResources(), R.drawable.miecz1),
			 BitmapFactory.decodeResource(getResources(), R.drawable.miecz2),
			 BitmapFactory.decodeResource(getResources(), R.drawable.miecz3)
	 };
	 Bitmap _panel = BitmapFactory.decodeResource(getResources(), R.drawable.panel);
	 
	GameObject hobgoblin = new Monster();
	Monster szkielet = new Monster();
	Monster kobold = new Monster();
	Weapon sword1 = new Weapon();
	Weapon sword2 = new Weapon();
	Weapon sword3 = new Weapon();
	Weapon sword4 = new Weapon();
	Wall wall1 = new  Wall();
	Bitmap _zbroja=BitmapFactory.decodeResource(getResources(), R.drawable.zbroja_kolkowa);
	Bitmap _miecz=BitmapFactory.decodeResource(getResources(), R.drawable.sztylet2);
		
	
    public Direct facing=Direct.SOUTH;
    
	public static int[][] mapa = new int[][]
			   {{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
				{1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
				{1,0,0,1,0,1,0,0,0,1,1,0,0,0,1,0,0,1},
				{1,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0,0,1},
				{1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,0,0,1},
				{1,1,0,0,0,0,1,0,0,1,0,0,0,1,1,0,0,1},
				{1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,1},
				{1,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1},
				{1,1,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1},
				{1,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1},
				{1,1,0,1,0,0,0,1,0,0,0,0,0,1,0,0,1,1},
				{1,1,1,1,0,0,0,1,0,0,0,1,0,1,0,0,1,1},
				{1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,1},
				{1,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,1,1},
				{1,0,1,1,1,0,1,1,0,0,1,1,1,1,0,0,1,1},
				{1,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,1,1},
				{1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1},
				{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}};
    
	public int[][] monstersMap = new int[MAX_X][MAX_Y];
	
	class AnimationThread extends Thread {
      
        public static final int DIFFICULTY_EASY = 0;
        public static final int DIFFICULTY_HARD = 1;
        public static final int DIFFICULTY_MEDIUM = 2;
       
        public static final int STATE_LOSE = 1;
        public static final int STATE_PAUSE = 2;
        public static final int STATE_READY = 3;
        public static final int STATE_RUNNING = 4;
        public static final int STATE_WIN = 5;

        private static final String KEY_DIFFICULTY = "mDifficulty";
        private static final String KEY_WINS = "mWinsInARow";
        
        private ArrayList<AnimatedSprite> mSprites;
        private ArrayList<AnimatedSprite> mSpritestoRemove;
       
        private Bitmap b;
        
        private int mDifficulty;
        private Handler mHandler;
        private int mMode;
        private long mLastTime;
        private boolean mRun = false;
        private int frameSamplesCollected = 0;
        private int frameSampleTime = 0;
        private int fps = 0;
        private SurfaceHolder mSurfaceHolder;
        private Paint textPaint;
        private int numSprites;
        private Resources res;
    
        public AnimationThread(SurfaceHolder surfaceHolder, Context context, Handler handler) {
            mSurfaceHolder = surfaceHolder;
            mHandler = handler;
            mContext = context;

            res = context.getResources();

            mSprites = new ArrayList<AnimatedSprite>();                        
            mSpritestoRemove = new ArrayList<AnimatedSprite>();
                        
            textPaint = new Paint();
            textPaint.setARGB(255,255,255,255);
            textPaint.setTextSize(16);
            
            numSprites = 0;
            mDifficulty = DIFFICULTY_MEDIUM;      
        }
        @Override
        public void run() {
            while (mRun) {
                Canvas c = null;
                try {
                    c = mSurfaceHolder.lockCanvas(null);
                    synchronized (mSurfaceHolder) {
                    	
                        if (mMode == STATE_RUNNING) 
                        	updatePhysics();
                        
                        doDraw(c);
                    }
                } catch(Exception e){
                	System.out.println(e.getStackTrace());
                }finally {
                    if (c != null) {
                        mSurfaceHolder.unlockCanvasAndPost(c);
                    }
                }
            }
        }   
        /**
         * Draws to the provided Canvas.
         * @param PosX, int PosY 
         */
        private void doDraw(Canvas canvas) {
        	int x,y;
        	x=szkielet.posX;
            y=szkielet.posY;
        	if (szkielet.move(mapa,PosX,PosY)!=0)
        	{
        		monstersMap[x][y]=0;
        		monstersMap[szkielet.posX][szkielet.posY]=1;
        	}
        	x=kobold.posX;
        	y=kobold.posY;
        	if (kobold.move(mapa,PosX,PosY)!=0)
        	{
        		monstersMap[x][y]=0;
        		monstersMap[kobold.posX][kobold.posY]=2;
        	}
        	
        	canvas.save();
        	canvas.drawColor(Color.BLACK);
        	
        	canvas.drawBitmap(_tlo, 0, 0, null);
        	
			switch (facing)
        	{
        	case NORTH:
        		switch(MonsterInRange(PosX+1, PosY-3))
        		{
        		case 1:
        			szkielet.draw(canvas, skel, Direct.NORTH, 0.70f,380, 105);
        		break;
        		case 2:
        			kobold.draw(canvas, kob, Direct.NORTH, 0.70f,380, 105);
        		break;
        		}
        		
        		wall1.draw(canvas, mapa, PosX+2,  PosY-3,427, 83,_s3p);
        		wall1.draw(canvas, mapa, PosX+1, PosY-3,276, 83,_s3p);
        		switch(MonsterInRange(PosX-1, PosY-3))
        		{
        		case 1:
        			szkielet.draw(canvas, skel, Direct.NORTH, 0.70f,30, 105);
        		break;
        		case 2:
        			kobold.draw(canvas, kob, Direct.NORTH, 0.70f,30, 105);
        		break;
        		}
        		  
        		wall1.draw(canvas, mapa, PosX-1, PosY-3,9, 83,_s3l);
        		switch(MonsterInRange(PosX, PosY-3))
        		{
        		case 1:
        			szkielet.draw(canvas, skel, Direct.NORTH, 0.70f,205, 105);
        		break;
        		case 2:
        			kobold.draw(canvas, kob, Direct.NORTH, 0.70f,205, 105);
        		break;
        		}
        		wall1.draw(canvas, mapa, PosX, PosY-3,156, 83,_s3m);
        		switch(MonsterInRange(PosX-1, PosY-2))
        		{
        		case 1:
        			szkielet.draw(canvas, skel, Direct.NORTH, 1f,40, 85);
        		break;
        		case 2:
        			kobold.draw(canvas, kob, Direct.NORTH, 1f,40, 85);
        		break;
        		}
        		wall1.draw(canvas, mapa, PosX-1, PosY-2,0, 60,_s2l);
        		switch(MonsterInRange(PosX+1, PosY-2))
        		{
        		case 1:
        			szkielet.draw(canvas, skel, Direct.NORTH, 1f,370, 85);
        		break;
        		case 2:
        			kobold.draw(canvas, kob, Direct.NORTH, 1f,370, 85);
        		break;
        		}
        		wall1.draw(canvas, mapa, PosX+1, PosY-2,301, 60,_s2p);
        		switch(MonsterInRange(PosX, PosY-2))
        		{
        		case 1:
        			szkielet.draw(canvas, skel, Direct.NORTH, 1f,205, 85);
        		break;
        		case 2:
        			kobold.draw(canvas, kob, Direct.NORTH, 1f,205, 85);
        		break;
        		}
        		wall1.draw(canvas, mapa, PosX, PosY-2,110, 60,_s2m);
        		switch(MonsterInRange(PosX-1, PosY-1))
        		{
        		case 1:
        			szkielet.draw(canvas, skel, Direct.NORTH, 1.5f,20, 85);
        		break;
        		case 2:
        			kobold.draw(canvas, kob, Direct.NORTH, 1.5f,20, 85);
        		break;
        		}
        		wall1.draw(canvas, mapa, PosX-1, PosY-1,0, 24,_s1l);
        		switch(MonsterInRange(PosX+1, PosY-1))
        		{
        		case 1:
        			szkielet.draw(canvas, skel, Direct.NORTH, 1.5f,360, 85);
        		break;
        		case 2:
        			kobold.draw(canvas, kob, Direct.NORTH, 1.5f,360, 85);
        		break;
        		}
        		wall1.draw(canvas, mapa, PosX+1, PosY-1,348, 24,_s1p);
        		switch(MonsterInRange(PosX, PosY-1))
        		{
        		case 1:
        			szkielet.draw(canvas, skel, Direct.NORTH, 1.5f,180, 85);
        		break;
        		case 2:
        			kobold.draw(canvas, kob, Direct.NORTH, 1.5f,180, 85);
        		break;
        		}
        		wall1.draw(canvas, mapa, PosX, PosY-1,48, 24,_s1m);
        		wall1.draw(canvas, mapa, PosX-1, PosY,0, 0,_s0l);
        		sword4.draw(canvas,miecz,0, 20,300);
        		sword1.setShow(false);
        		sword2.setShow(false);
        		sword3.setShow(false);
        		
        		
        		wall1.draw(canvas, mapa, PosX+1, PosY,412, 0,_s0p);
        		switch(MonsterInRange(PosX, PosY))
        		{
        		case 1:
            		szkielet.draw(canvas, skel, Direct.NORTH, 2f,180, 85);
            	break;
        		case 2:
        			kobold.draw(canvas, kob, Direct.NORTH, 2f,180, 85);
        		break;
        		}
        	break;
        	case EAST:
        		if(MonsterInRange(PosX+3, PosY+1)!=0)
        		  szkielet.draw(canvas, skel, Direct.EAST, 0.70f,380, 105);
        		wall1.draw(canvas, mapa, PosX+3,  PosY+2,427, 83,_s3p);
        		wall1.draw(canvas, mapa, PosX+3, PosY+1,276, 83,_s3p);
        		if(MonsterInRange(PosX+3, PosY-1)!=0)
        		  szkielet.draw(canvas, skel, Direct.EAST, 0.70f,30, 105);
        		wall1.draw(canvas, mapa, PosX+3, PosY-1,9, 83,_s3l);
        		if(MonsterInRange(PosX+3, PosY)!=0)
        		 szkielet.draw(canvas, skel, Direct.EAST, 0.70f,205, 105);
        		wall1.draw(canvas, mapa, PosX+3, PosY,156, 83,_s3m);
        		if(MonsterInRange(PosX+2, PosY-1)!=0)
        		  szkielet.draw(canvas, skel, Direct.EAST, 1f,40, 85);
        		wall1.draw(canvas, mapa, PosX+2, PosY-1,0, 60,_s2l);
        		if(MonsterInRange(PosX+2, PosY+1)!=0)
        		  szkielet.draw(canvas, skel, Direct.EAST, 1f,370, 85);
        		wall1.draw(canvas, mapa, PosX+2, PosY+1,301, 60,_s2p);
        		if(MonsterInRange(PosX+2, PosY)!=0)
        		  szkielet.draw(canvas, skel, Direct.EAST, 1f,205, 85);
        		wall1.draw(canvas, mapa, PosX+2, PosY,110, 60,_s2m);
        		if(MonsterInRange(PosX+1, PosY-1)!=0)
        		szkielet.draw(canvas, skel, Direct.EAST, 1.5f,20, 85);
        		wall1.draw(canvas, mapa, PosX+1, PosY-1,0, 24,_s1l);
        		if(MonsterInRange(PosX+1, PosY+1)!=0)
        		szkielet.draw(canvas, skel, Direct.EAST, 1.5f,360, 85);
        		wall1.draw(canvas, mapa, PosX+1, PosY+1,348, 24,_s1p);
        		if(MonsterInRange(PosX+1, PosY)!=0)
        		szkielet.draw(canvas, skel, Direct.EAST, 1.5f,180, 85);
        		wall1.draw(canvas, mapa, PosX+1, PosY,48, 24,_s1m);
        		
        		wall1.draw(canvas, mapa, PosX, PosY-1,0, 0,_s0l);
				sword1.draw(canvas, miecz, 1, 20, 300);
		 		sword2.setShow(false);
        		sword3.setShow(false);
        		sword4.setShow(false);
        		wall1.draw(canvas, mapa, PosX, PosY+1, 412,0,_s0p);
        		if(MonsterInRange(PosX, PosY)!=0)
            		szkielet.draw(canvas, skel, Direct.EAST, 2f,180, 85);
        	break;
        	case SOUTH:
        		if(MonsterInRange(PosX-1, PosY+3)!=0)
        		  szkielet.draw(canvas, skel, Direct.SOUTH, 0.70f,380, 105);
        		wall1.draw(canvas, mapa, PosX-2, PosY+3,427, 83,_s3p);
        		wall1.draw(canvas, mapa, PosX-1, PosY+3,276, 83,_s3p);
        		if(MonsterInRange(PosX+1, PosY+3)!=0)
        		  szkielet.draw(canvas, skel, Direct.SOUTH, 0.70f,30, 105);
        		wall1.draw(canvas, mapa, PosX+1, PosY+3,9, 83,_s3l);
        		if(MonsterInRange(PosX, PosY+3)!=0)
        		  szkielet.draw(canvas, skel, Direct.SOUTH, 0.70f,205, 105);
        		wall1.draw(canvas, mapa, PosX, PosY+3,156, 83,_s3m);
        		if(MonsterInRange(PosX+1, PosY+2)!=0)
        		  szkielet.draw(canvas, skel, Direct.SOUTH, 1f,40, 85);
        		wall1.draw(canvas, mapa, PosX+1, PosY+2,0, 60,_s2l);
        		if(MonsterInRange(PosX-1, PosY+2)!=0)
        		  szkielet.draw(canvas, skel, Direct.SOUTH, 1f,370, 85);
        		wall1.draw(canvas, mapa, PosX-1, PosY+2,301, 60,_s2p);
        		if(MonsterInRange(PosX, PosY+2)!=0)
        		  szkielet.draw(canvas, skel, Direct.SOUTH, 1f,205, 85);
        		wall1.draw(canvas, mapa, PosX, PosY+2,110, 60,_s2m);
        		
        		if(MonsterInRange(PosX+1, PosY+1)!=0)
        		  szkielet.draw(canvas, skel, Direct.SOUTH, 1.5f,20, 85);
        		wall1.draw(canvas, mapa, PosX+1, PosY+1,0, 24,_s1l);
        		if(MonsterInRange(PosX-1, PosY+1)!=0)
        		  szkielet.draw(canvas, skel, Direct.SOUTH, 1.5f,360, 85);
        		wall1.draw(canvas, mapa, PosX-1, PosY+1,348, 24,_s1p);
        		if(MonsterInRange(PosX, PosY+1)!=0)
        		  szkielet.draw(canvas, skel, Direct.SOUTH, 1.5f,180, 85);
        		wall1.draw(canvas, mapa, PosX, PosY+1,48, 24,_s1m);
        		
        		wall1.draw(canvas, mapa, PosX+1, PosY,0, 0,_s0l);
        		sword2.draw(canvas, miecz, 2, 20, 300);     
        		sword1.setShow(false);
        		sword3.setShow(false);
        		sword4.setShow(false);
        	
        		wall1.draw(canvas, mapa, PosX-1, PosY,412, 0,_s0p);
        		if(MonsterInRange(PosX, PosY)!=0)
            		szkielet.draw(canvas, skel, Direct.SOUTH, 2f,180, 85);
        	break;
        	case WEST:
        		if(MonsterInRange(PosX-3, PosY-1)!=0)
        		szkielet.draw(canvas, skel, Direct.WEST, 0.70f,380, 105);
        		wall1.draw(canvas, mapa, PosX-3,  PosY-2,427, 83,_s3p);
        		wall1.draw(canvas, mapa, PosX-3, PosY-1,276, 83,_s3p);
        		if(MonsterInRange(PosX-3, PosY+1)!=0)
        		szkielet.draw(canvas, skel, Direct.WEST, 0.70f,30, 105);
        		wall1.draw(canvas, mapa, PosX-3, PosY+1,9, 83,_s3l);
        		if(MonsterInRange(PosX-3, PosY)!=0)
        		szkielet.draw(canvas, skel, Direct.WEST, 0.70f,205, 105);
        		wall1.draw(canvas, mapa, PosX-3, PosY,156, 83,_s3m);
        		if(MonsterInRange(PosX-2, PosY+1)!=0)
        		  szkielet.draw(canvas, skel, Direct.WEST, 1f,40, 85);
        		wall1.draw(canvas, mapa, PosX-2, PosY+1,0, 60,_s2l);
        		if(MonsterInRange(PosX+2, PosY)!=0)
        		  szkielet.draw(canvas, skel, Direct.WEST, 1f,370, 85);
        		wall1.draw(canvas, mapa, PosX+2, PosY,301, 60,_s2p);
        		if(MonsterInRange(PosX-2, PosY)!=0)
        		  szkielet.draw(canvas, skel, Direct.WEST, 1f,205, 85);
        		wall1.draw(canvas, mapa, PosX-2, PosY,110, 60,_s2m);
        		if(MonsterInRange(PosX-1, PosY+1)!=0)
        		  szkielet.draw(canvas, skel, Direct.WEST, 1.5f,20, 85);
        		wall1.draw(canvas, mapa, PosX-1, PosY+1,0, 24,_s1l);
        		if(MonsterInRange(PosX-1, PosY-1)!=0)
        		  szkielet.draw(canvas, skel, Direct.WEST, 1.5f,360, 85);
        		wall1.draw(canvas, mapa, PosX-1, PosY-1,348, 24,_s1p);
        		  if(MonsterInRange(PosX-1, PosY)!=0)
        		szkielet.draw(canvas, skel, Direct.WEST, 1.5f,180, 85);
        		wall1.draw(canvas, mapa, PosX-1, PosY,48, 24,_s1m);
        		
        		wall1.draw(canvas, mapa, PosX, PosY+1,0, 0,_s0l);
        		sword3.draw(canvas, miecz, 3, 20, 300);
         		sword1.setShow(false);
        		sword2.setShow(false);
        		sword4.setShow(false);
        		wall1.draw(canvas, mapa, PosX, PosY-1, 412,0,_s0p);
        		if(MonsterInRange(PosX, PosY)!=0)
            		szkielet.draw(canvas, skel, Direct.WEST, 2f,180, 85);
        	break;
        	}
        	canvas.drawBitmap(_panel, 20,360, null);
            canvas.restore();
           //canvas.drawBitmap(a,100,100)
        	  for( AnimatedSprite a : mSprites)
        	  {
        		a.draw(canvas);
        	  } 
        	 /*
        	  if (komunikat=="Zbroja")
        		  if (Armored==false)
        		  {
        		  canvas.drawBitmap(_zbroja,151,453, null); 
        		  }
        		  else
        		  {
        			canvas.drawBitmap(_zbroja,395,405, null);	
        		  }
        	  if (komunikat=="Miecz")
        		  canvas.drawBitmap(_miecz, 20,491, null);
        	  */
        	
        	if(mMode == STATE_RUNNING )
        	{
        		String direct = null;
        		//canvas.drawText(cX + " zone X", getWidth() - 60, getHeight() - 0, textPaint);
        		//canvas.drawText(cY + " zone Y", getWidth() - 60, getHeight() - 20, textPaint);
        		switch (facing)
        		{
        		case NORTH:
        			direct = "north";
        	    break;
        		case EAST:
        			direct="east";
        		break;
        		case SOUTH:
        			direct = "south";
        			break;
        		case WEST:
        			direct = "west";
        		break;
        		
        		}
        		canvas.drawText( direct, getWidth() - 60, getHeight() - 20, textPaint);
        		//canvas.drawText(PosY + " pos Y", getWidth() - 60, getHeight() - 60, textPaint);
	        	//canvas.drawText(PosX + " pos X", getWidth() - 60, getHeight() - 40, textPaint);
	        	canvas.drawText("X = "+cX, getWidth() - 60, getHeight() - 60, textPaint);
	        	canvas.drawText("Y = "+cY, getWidth() - 60, getHeight() -40, textPaint);
	        	//canvas.drawText(komunikat, getWidth() - 60, getHeight() - 80, textPaint);
        	}
        	canvas.restore();
        }
        
        private int MonsterInRange( int p_x, int p_y)
        {
        	int wynik = 0;
        	if ((p_x>MIN_X && p_x<MAX_X) && (p_y>MIN_Y && p_y<MAX_Y))	// w granicach mapy
        		 if ((monstersMap[p_x][p_y]!=0))
        		   wynik = monstersMap[p_x][p_y];
        	return wynik;
        }
        
        private void updatePhysics()
        {
            long now = System.currentTimeMillis();

            if (mLastTime > now) return;
            
            if (mLastTime != 0)
            {
        		int time = (int) (now - mLastTime);
        		frameSampleTime += time;
        		frameSamplesCollected++;
        		if (frameSamplesCollected == 10)
        		{
	        		fps = (int) (10000 / frameSampleTime);
	        		frameSampleTime = 0;
	        		frameSamplesCollected = 0;
        		}        		
        	}
            
            synchronized(mSprites){
	            for( AnimatedSprite a : mSprites){
	            	a.Update(now);
	            	
	            	if(a.dispose)
	            		mSpritestoRemove.add(a);            	
	            }
            }
            
            synchronized(mSpritestoRemove){
	            mSprites.removeAll(mSpritestoRemove); 
	            mSpritestoRemove.clear();
            }
            
            numSprites = mSprites.size();
            mLastTime = now;      
        }
        
        /**
         * Detected touch event
         * @param e
         */
        public void doTouch(MotionEvent event)
        {
        	//AnimatedSprite FirstItem;
        	
        	int action = event.getAction();
            float x = event.getX();  // or getRawX();
            float y = event.getY();
            
            switch(action)
            {
            case MotionEvent.ACTION_DOWN:
            	if(mMode != STATE_RUNNING)
            		setState(STATE_RUNNING);
            	else if(mMode == STATE_RUNNING)
            	{
            		cX=(int)x;
            		cY=(int)y;
            		
            		/*
            		Boolean nic=true;
            		if ( ((cY>454) && (cY<531)) && ( (cX>150) && (cX<230)) )
            		{
            		  nic=false;
            		  komunikat="Zbroja";
            		  if(Armored)
            			  Armored=false;
            		  else
            		    Armored=true;
            		}
            		if ( ((cY>491) && (cY<575)) && ( (cX>22) && (cX<100)) ) 
            		{
            		  nic=false;
              		  komunikat="Miecz";
            		}
            		if (nic)
              			  komunikat="";
              	    */
            		/*
            		AnimatedSprite a = new AnimatedSprite();
            			//mItemSprite = new AnimatedSprite();
            		if(b == null)
            			b = BitmapFactory.decodeStream(res.openRawResource(R.drawable.zbroja_kolkowa));         		
            
            		a.Initialize(b, 65, 65, 10, 1, true);
            		
            		a.setXPos((int)x);
            		a.setYPos((int)y);
            		
            		
            		//a.Update(now);
            		 synchronized(mSprites)
                     {
            			 mSprites.add(a);
            			 FirstItem=mSprites.get(0);
            			// if (FirstItem!=null)
            			 FirstItem.setXPos((int)x);
            			 FirstItem.setYPos((int)y);
            			 if (a!=FirstItem)	 
            			 {
            			 mSpritestoRemove.add(a);
            			 }	
             		 }*/
                       	
            	break;
                }
             
            }
        }
        /**
         * @param mode one of the STATE_* constants
         * @param message string to add to screen or null
         */
        public void setState(int mode, CharSequence message) {

            synchronized (mSurfaceHolder) {
                mMode = mode;

                if (mMode == STATE_RUNNING) {
                    Message msg = mHandler.obtainMessage();
                    Bundle b = new Bundle();
                    b.putString("text", "");
                    b.putInt("viz", View.INVISIBLE);
                    msg.setData(b);
                    mHandler.sendMessage(msg);
                } else {
                   
                    Resources res = mContext.getResources();
                    CharSequence str = "";
                    if (mMode == STATE_READY)
                        str = res.getText(R.string.mode_ready);
                    else if (mMode == STATE_PAUSE)
                        str = res.getText(R.string.mode_pause);
                    else if (mMode == STATE_LOSE)
                        str = res.getText(R.string.mode_lose);
                    else if (mMode == STATE_WIN)
                        str = res.getString(R.string.mode_win_prefix)
                                + numSprites + " "
                                + res.getString(R.string.mode_win_suffix);

                    if (message != null) {
                        str = message + "\n" + str;
                    }

                    if (mMode == STATE_LOSE) numSprites = 0;

                    Message msg = mHandler.obtainMessage();
                    Bundle b = new Bundle();
                    b.putString("text", str.toString());
                    b.putInt("viz", View.VISIBLE);
                    msg.setData(b);
                    mHandler.sendMessage(msg);
                }
            }
        }
        /** 
         * @return Bundle with this view's state
         */
        public Bundle saveState(Bundle map) {
            synchronized (mSurfaceHolder) {
                if (map != null) {
                    map.putInt(KEY_DIFFICULTY, Integer.valueOf(mDifficulty));                    
                    map.putInt(KEY_WINS, Integer.valueOf(numSprites));
                }
            }
            return map;
        }

        /**
         * Sets the current difficulty.
         * 
         * @param difficulty
         */
        public void setDifficulty(int difficulty) {
            synchronized (mSurfaceHolder) {
                mDifficulty = difficulty;
            }
        }

        /**
         * @param b true to run, false to shut down
         */
        public void setRunning(boolean b) {
            mRun = b;
        }

        /**
         * @see #setState(int, CharSequence)
         * @param mode one of the STATE_* constants
         */
        public void setState(int mode) {
            synchronized (mSurfaceHolder) {
                setState(mode, null);
            }
        }

        /* Callback invoked when the surface dimensions change. */
        public void setSurfaceSize(int width, int height) {
            // synchronized to make sure these all change atomically
            synchronized (mSurfaceHolder) {
            }
        }
        /**
         * Resumes from a pause.
         */
        public void unpause() {
            // Move the real time clock up to now
            synchronized (mSurfaceHolder) {
                mLastTime = System.currentTimeMillis() + 100;
            }
            setState(STATE_RUNNING);
        }
        
        public void doStart() {
            synchronized (mSurfaceHolder) {               
                mLastTime = System.currentTimeMillis() + 100;
                setState(STATE_RUNNING);
            }
        }
        /**
         * Pauses the physics update & animation.
         */
        public void pause() {
            synchronized (mSurfaceHolder) {
                if (mMode == STATE_RUNNING) setState(STATE_PAUSE);
            }
        }

        /**
         * @param savedState Bundle containing the game state
         */
        public synchronized void restoreState(Bundle savedState) {
            synchronized (mSurfaceHolder) {
                setState(STATE_PAUSE);         

                mDifficulty = savedState.getInt(KEY_DIFFICULTY);               
                numSprites = savedState.getInt(KEY_WINS);
            }
        }

		public void clearSprites() {
			synchronized(mSprites){
				mSprites.clear();			
			}
		}   
    }

    /** Handle to the application context, used to e.g. fetch Drawables. */
    private Context mContext;

    /** Pointer to the text view to display "Paused.." etc. */
    private TextView mStatusText;

    /** The thread that actually draws the animation */
    private AnimationThread thread;

    public AnimationView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        // register our interest in hearing about changes to our surface
        SurfaceHolder holder = getHolder();
        holder.addCallback(this);

        // create thread only; it's started in surfaceCreated()
        thread = new AnimationThread(holder, context, new Handler()
        {
            @Override
            public void handleMessage(Message m)
            {
                mStatusText.setVisibility(m.getData().getInt("viz"));
                mStatusText.setText(m.getData().getString("text"));
            }
        });

        setFocusable(true); // make sure we get key events
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event){
    	thread.doTouch(event);
    	return super.onTouchEvent(event);
    }

	/**
     * Fetches the animation thread corresponding to this LunarView.
     * 
     * @return the animation thread
     */
    public AnimationThread getThread() {
        return thread;
    }

    /**
     * Standard window-focus override. Notice focus lost so we can pause on
     * focus lost. e.g. user switches to take a call.
     */
    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        if (!hasWindowFocus) thread.pause();
    }

    /**
     * Installs a pointer to the text view used for messages.
     */
    public void setTextView(TextView textView) {
        mStatusText = textView;
    }

    /* Callback invoked when the surface dimensions change. */
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        thread.setSurfaceSize(width, height);
    }
    /*
     * Callback invoked when the Surface has been created and is ready to be
     * used.
     */
    public void surfaceCreated(SurfaceHolder holder) {
        // start the thread here so that we don't busy-wait in run()
        // waiting for the surface to be created
        thread.setRunning(true);
        thread.start();
    }
    /*
     * Callback invoked when the Surface has been destroyed and must no longer
     * be touched. WARNING: after this method returns, the Surface/Canvas must
     * never be touched again!
     */
    public void surfaceDestroyed(SurfaceHolder holder) {
        // we have to tell thread to shut down & wait for it to finish, or else
        // it might touch the Surface after we return and explode
        boolean retry = true;
        thread.setRunning(false);
        while (retry) {
            try {
                thread.join();
                retry = false;
            } catch (InterruptedException e) {
            }
        }
    }
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
    	if(keyCode == android.view.KeyEvent.KEYCODE_DPAD_LEFT )
        {
    		switch(facing)
    		{
    		case NORTH:
    			facing=Direct.WEST;  
    			break;
    		case WEST:
    			facing=Direct.SOUTH;
    			break;
    		case SOUTH:
    			facing=Direct.EAST;
    			break;
    		case EAST:
    			facing=Direct.NORTH;
    			break;
    		default:
    			break;
    		}
        }
    	if(keyCode == android.view.KeyEvent.KEYCODE_DPAD_RIGHT)
        {
    		switch(facing)
    		{
    		case NORTH:
    			facing=Direct.EAST;  
    			break;
    		case EAST:
    			facing=Direct.SOUTH;
    			break;
    		case SOUTH:
    			facing=Direct.WEST;
    			break;
    		case WEST:
    			facing=Direct.NORTH;
    			break;
    		default:
    			break;
    		}
        }
    	if(keyCode == android.view.KeyEvent.KEYCODE_DPAD_UP )
        {
    		switch(facing)
    		{
    		case NORTH:
    			if(mapa[PosX][PosY-1]==0)
    			PosY--;
    			break;
    		case EAST:
    			if(mapa[PosX+1][PosY]==0)
    			PosX++;
    			break;
    		case SOUTH:
    			if(mapa[PosX][PosY+1]==0)
    			PosY++;
    			break;
    		case WEST:
    			if(mapa[PosX-1][PosY]==0)
    			PosX--;
    			break;
    			default:
    			break;
    		}   
        }
    	if(keyCode == android.view.KeyEvent.KEYCODE_DPAD_DOWN )
        {
    		switch(facing)
    		{
    		case NORTH:
    			if(mapa[PosX][PosY+1]==0)
    			PosY++;
    			break;
    		case EAST:
    			if(mapa[PosX-1][PosY]==0)
    			PosX--;
    			break;
    		case SOUTH:
    			if(mapa[PosX][PosY-1]==0)
    			PosY--;
    			break;
    		case WEST:
    			if(mapa[PosX+1][PosY]==0)
    			PosX++;
    			break;
    			default:
    			break;
    		}
        }
    	if(keyCode == android.view.KeyEvent.KEYCODE_Z)
    	{
    		if(sword1.isShow())
    		{
    			sword1.setHiden(true);    	
    		
    		}
    		if(sword2.isShow())
    		{
    			sword2.setHiden(true);    	
    		}
    		if(sword3.isShow())
    		{
				sword3.setHiden(true);    	
    		
    		}
    		if(sword4.isShow())
    		{
				sword4.setHiden(true);    	
    		
    		}
    	}
    	
    return super.onKeyDown(keyCode,event);
    }
	
	
	public int kostka(int IleScianek)
	{
		Random rand = new Random();
		return rand.nextInt(IleScianek) + 1;
	}
}
